//#define _CRT_SECURE_NO_WARNINGS 2

#include"DList.h"

 ListNode* AddNode(datatype val) {
	 ListNode* newnode = (ListNode*)malloc(sizeof( ListNode));
	if (!newnode) {
		perror("newnode malloc");
		return NULL;
	}
	newnode->next = NULL;
	newnode->pre = NULL;
	newnode->data = val;
	return  newnode;
}

  
 ListNode* Init() {
	ListNode* head = AddNode(-1);
	head->next = head;
	head->pre = head;
	head->data = -1;
	return head;
}

void firstPush(ListNode* phead, ListNode* newnode) {
	phead->next = phead->pre = newnode;
	newnode->next = newnode->pre = phead;
}
void PushFront(ListNode* phead,datatype val) {
	ListNode* newnode = AddNode(val);
	if (phead->next == phead && phead->pre == phead) {
		firstPush(phead, newnode);
		return;
	}
	ListNode* next = phead->next;
	phead->next = newnode;
	newnode->pre = phead;
	newnode->next = next;
	next->pre = newnode;
	//Insert(phead->next, val);
}

void PushBack(ListNode* phead, datatype val) {
	ListNode* newnode = AddNode(val);
	if (phead->next == phead && phead->pre == phead) {
		firstPush(phead, newnode);
		return;
	}

	/*phead->pre->next = newnode;
	newnode->pre = phead->pre->next;
	phead->pre = newnode;
	newnode->next = phead;*/
	newnode->pre = phead->pre;
	newnode->next = phead;
	phead->pre->next = newnode;
	phead->pre = newnode;
	//Insert(phead->pre, val);
}



void Print(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		printf("%d->",cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void PrintReverse(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->pre;
	while (cur != phead) {
		printf("%d->", cur->data);
		cur = cur->pre;
	}
	printf("NULL\n");
}

void PopFront(ListNode* phead) {
	assert(!(phead->next==phead));
	assert(phead);
	ListNode* head = phead->next;
	phead->next = phead->next->next;
	phead->next->pre = phead;
	free(head);
	//Erase(phead->next);
}

void PopBack(ListNode* phead) {
	assert(phead);
	assert(!(phead->next == phead));
	/*ListNode* tail = phead->pre;
	phead->pre = tail->pre;
	tail->pre->next = phead;
	free(tail);*/
	ListNode* tail = phead->pre;
	ListNode* tailPrev = tail->pre;

	
	tailPrev->next = phead;
	phead->pre = tailPrev;
	free(tail);
	tail = NULL;
	//Erase(phead->pre);
}

ListNode* Find(ListNode* phead, datatype val) {
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data != val) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void Insert(ListNode* pos, datatype val) {
	ListNode* newnode = AddNode(val);
	pos->pre->next = newnode;
	newnode->pre = pos->pre;
	pos->pre = newnode;
	newnode->next = pos;
}

void Erase(ListNode* pos) {
	pos->pre->next = pos->next;
	pos->next->pre = pos->pre;
	free(pos);
}

void Destry(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}
